//#region
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  message,
  Select,
} from 'antd'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { useStore } from '@/store'
import { useEffect, useRef, useState } from 'react'
import './index'
import { http } from '@/utils'
const { Option } = Select
//#endregion
const Publish = () => {
  const [params] = useSearchParams()
  const articleId = params.get('id')
  // 获取频道列表
  const [value, setValue] = useState(1)
  const [fileList, setFileList] = useState([])
  const [imgCount, setImgCount] = useState(1)
  const [channel, setChannal] = useState([])
  const navigate = useNavigate()
  // 获取渠道列表
  useEffect(() => {
    async function channelList() {
      const res = await http.get('/channels')
      setChannal(res.data.data.channels)
    }
    channelList()
  }, [])
  // 1. 声明一个暂存仓库
  const fileListRef = useRef([])
  // 上传成功回调
  const onUploadChange = (info) => {
    const fileList = info.fileList.map((file) => {
      // 上传完毕 做数据处理
      if (file.response) {
        return {
          url: file.response.data.url,
        }
      }
      // 否则在上传中时，不做处理
      return file
    })
    setFileList(fileList)
    fileListRef.current = fileList
  }
  // 修改图片模式（单图，三图，无图）
  const changeType = (e) => {
    const count = e.target.value
    setImgCount(count)
    if (count === 1) {
      // 如果是单图,只显示第一张
      const fileImg = fileListRef.current[0]
      setFileList(!fileImg ? [] : [fileImg])
    } else if (count === 3) {
      // 三图展示全部图片
      setFileList(fileListRef.current)
    }
  }

  // 获取form实例
  const form = useRef(null)
  // 编辑的话，获取数据，返显 . id调用接口  2.暂存列表  3.UpLoad组件fileList
  useEffect(() => {
    async function getAtricle() {
      const res = await http.get(`/mp/articles/${articleId}`)
      form.current.setFieldsValue({
        ...res.data.data,
        type: res.data.data.cover.type,
      })
      const pictList = res.data.data.cover.images.map((url) => {
        return {
          url,
        }
      })
      setFileList(pictList)
      // 暂存里也放一份（暂存列表和fileList列表保持统一就可以）
      fileListRef.current = pictList
      // 当无图时不显示upload框
      if (pictList.length == 0) {
        setImgCount(0)
      }
    }
    if (articleId) {
      getAtricle()
    }
  }, [])
  // 提交
  const onSubmit = async (values) => {
    const { channel_id, content, title, type } = values
    const _images = fileList.map((item) => item.url)
    const params = {
      channel_id,
      content,
      title,
      type,
      cover: {
        type,
        images: _images,
      },
    }
    if (articleId) {
      // 编辑
      await http.put(`/mp/articles/${articleId}?draft=false`, params)
    } else {
      // 添加
      await http.post('/mp/articles?draft=false', params)
    }
    // 跳转到内容管理
    navigate('/article')
    message.success(articleId ? '编辑成功！' : '添加成功！')
  }
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {articleId ? '修改文章' : '发布文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }>
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          onFinish={onSubmit}
          ref={form}
          // 注意：此处需要为富文本编辑表示的 content 文章内容设置默认值
          initialValues={{ type: 1, content: '' }}>
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}>
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}>
            <Select style={{ width: 120 }}>
              {channel.map((item) => (
                <Option value={item.id} key={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            <div style={{ marginTop: 10 }}>
              {imgCount > 0 && (
                <Upload
                  className="avatar-uploader"
                  name="image"
                  listType="picture-card"
                  showUploadList
                  action="http://geek.itheima.net/v1_0/upload"
                  fileList={fileList}
                  maxCount={imgCount} //做多上传图片数
                  multiple={imgCount > 1} //是否支持多选文件
                  onChange={onUploadChange}>
                  <div>
                    <PlusOutlined />
                    Upload
                  </div>
                </Upload>
              )}
            </div>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}>
            <ReactQuill
              className="publish-quill"
              theme="snow"
              value={value}
              onChange={setValue}
              placeholder="请输入文章内容"
            />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Button type="primary" htmlType="submit">
              {articleId ? '修改文章' : '发布文章'}
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
export default Publish
